package com.example.administrator.gaodemap;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.Projection;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;


public class MainActivity extends AppCompatActivity {

    private MyMapView mMapView;
    private AMap aMap;
    private UiSettings mUiSettings;
    private EditText mEditText;
    private FrameLayout mFrameLayout;
    private MovePathView1 mMovePathView1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFrameLayout = (FrameLayout) findViewById(R.id.fm);
        mMapView = (MyMapView) findViewById(R.id.map);

        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
//        改变地图默认显示区域  地图默认显示北京地区
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        //动态申请权限
        requestPermissions();
        initEvent();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initEvent() {
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {


            }

            //状态由变到不变
            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                Log.e("$zhw======$", "GGGGGG");

//                float zoom = cameraPosition.zoom;
                float scalePerPixel = aMap.getScalePerPixel();
                int pixel = (int) (100 / scalePerPixel);
                Log.e("$zhw======$", "pixel   " + pixel);
                if (pixel != 0) {
                    Constanst.PIXEL = pixel;
                }


            }
        });

        mMapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "111", Toast.LENGTH_SHORT).show();
            }
        });
        mMapView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Log.e("$zhw======$", "down");

                        break;
                    case MotionEvent.ACTION_MOVE:
                        Log.e("$zhw======$", "move");
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.e("$zhw======$", "up");
                        break;
                    default:
                        break;
                }

                return false;
            }
        });


    }

    private void startLocaion() {
//设置地图的放缩级别
        aMap.moveCamera(CameraUpdateFactory.zoomTo(13));
        MyLocationStyle myLocationStyle;
//初始化定位蓝点样式类
        myLocationStyle = new MyLocationStyle();
//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        initStyle(myLocationStyle);
//设置定位蓝点的Style
        aMap.setMyLocationStyle(myLocationStyle);
//设置默认定位按钮是否显示，非必需设置。
        aMap.getUiSettings().setMyLocationButtonEnabled(true);
// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        aMap.setMyLocationEnabled(true);
        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
//                Log.e("$zhw======$", "location  " + location.toString());

            }
        });
    }

    private void initStyle(MyLocationStyle myLocationStyle) {
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);
//设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.interval(Integer.MAX_VALUE);

//        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
//                fromResource(R.drawable.big));
//        myLocationStyle.strokeColor(Color.GREEN);
//        //自定义精度范围的圆形边框宽度
//        myLocationStyle.strokeWidth(5);
//        myLocationStyle.radiusFillColor(Color.GRAY);
//        aMap.setMyLocationStyle(myLocationStyle);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();


    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);

    }

    private void requestPermissions() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //自检已动态开启的权限
                int permission = ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION);
                //说明没有开启
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION}, 0x0010);
                } else {
                    startLocaion();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission Granted
            startLocaion();
        } else {
            // Permission Denied
        }

    }

    public void top(View view) {
        int height = mMapView.getHeight();
        int width = mMapView.getWidth();
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                width, height);
        mMovePathView1 = new MovePathView1(MainActivity.this);
        //textView的宽高包裹内容，不是父亲的宽高
        mFrameLayout.addView(mMovePathView1, params);
        //禁用地图
        mUiSettings.setAllGesturesEnabled(false);
        mUiSettings.setScaleControlsEnabled(true);
//        aMap.showIndoorMap(true);
        //设置缩放的按钮（+ -）
//mUiSettings.setZoomControlsEnabled(true);
//指南针
//        mUiSettings.setCompassEnabled(true);
//        mUiSettings.setMyLocationButtonEnabled(false); //显示默认的定位按钮
        //比例尺
//        mUiSettings.setScaleControlsEnabled(true);
//
//        每像素代表的实际地图距离
//        float scalePerPixel = aMap.getScalePerPixel();
//        Log.e("$zhw======$","scalePerPixel  "+scalePerPixel);
//        AMap.event.addListener(map,'zoomend',function(){
//            let scale = 20 - map.getZoom();
//            _this.scale = parseInt(Math.pow(2,scale))
//        });
        //缩放移动监听        地图状态改变的时候的回掉

        //缩放手势,滑动手势，旋转手势，倾斜手势，所有手势
//        setZoomGesturesEnabled，setZoomGesturesEnabled，setRotateGesturesEnabled，setTiltGesturesEnabled，setAllGesturesEnabled

        //参数依次是：视角调整区域的中心点坐标、希望调整到的缩放级别、俯仰角0°~45°（垂直与地图时为0）、偏航角 0~360° (正北方为0)
//        CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(39.977290,116.337000),18,30,0));
//        CameraUpdate mCameraUpdate1 = CameraUpdateFactory.zoomTo(17);
////        //设置中心点和缩放
//        aMap.moveCamera(mCameraUpdate);
//        aMap.moveCamera(mCameraUpdate1);

//        限制地图的显示范围
//        LatLng southwestLatLng = new LatLng(33.789925, 104.838326);
//        LatLng northeastLatLng = new LatLng(38.740688, 114.647472);
//        LatLngBounds latLngBounds = new LatLngBounds(southwestLatLng, northeastLatLng);
//        aMap.setMapStatusLimits(latLngBounds);
//        改变地图默认显示区域  地图默认显示北京地区


        //绘制标记物  还可以加动画哦  点击事件拖拽事件 以及自定义显示的内容
//        LatLng latLng = new LatLng(39.906901, 116.397972);
//        final Marker marker = aMap.addMarker(new MarkerOptions().position(latLng).title("北京").snippet("DefaultMarker"));
//        CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(39.906901, 116.397972), 18, 30, 0));
//        aMap.moveCamera(mCameraUpdate);
        //绘制线条
//        List<LatLng> latLngs = new ArrayList<LatLng>();
//        latLngs.add(new LatLng(39.999391,116.135972));
//        latLngs.add(new LatLng(39.898323,116.057694));
//        latLngs.add(new LatLng(39.900430,116.265061));
//        latLngs.add(new LatLng(39.955192,116.140092));
//        Polyline polyline = aMap.addPolyline(new PolylineOptions().
//                addAll(latLngs).width(10).color(Color.argb(255, 1, 1, 1)));
        //绘制圆，方形
//        LatLng latLng = new LatLng(39.984059,116.307771);
//        Circle circle = aMap.addCircle(new CircleOptions().
//                center(latLng).
//                radius(1000).
//                fillColor(Color.argb(100, 1, 1, 1)).
//                strokeColor(Color.argb(100, 1, 1, 1)).
//                strokeWidth(15));
//            aMap.getProjection().fromScreenLocation(new Point())


//坐标转换  其他坐标系转到高德坐标系


    }


    public void bottom(View view) {
//        LatLng mapCenterPoint = getMapCenterPoint();
//        Log.e("$zhw======$"," mapCenterPoint "+mapCenterPoint.latitude+"  "+mapCenterPoint.longitude);
//        DrawStadus.getIstance().setDrawCircle(true);
//        mUiSettings.setAllGesturesEnabled(false);

    }


    /**
     * by moos on 2017/09/05
     * func:获取屏幕中心的经纬度坐标
     *
     * @return
     */
    public LatLng getMapCenterPoint(int x, int y) {
        Projection projection = aMap.getProjection();
        LatLng pt = projection.fromScreenLocation(new Point(x, y));
        return pt;
    }

    public void start(View view) {
        delete(null);
        int height = mMapView.getHeight();
        int width = mMapView.getWidth();
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                width, height);
        mMovePathView1 = new MovePathView1(MainActivity.this);
        //textView的宽高包裹内容，不是父亲的宽高
        mFrameLayout.addView(mMovePathView1, params);
        //禁用地图
        mUiSettings.setAllGesturesEnabled(false);
        mUiSettings.setScaleControlsEnabled(true);
        Toast.makeText(this, "开始绘制", Toast.LENGTH_SHORT).show();
    }

    public void stop(View view) {
        Log.e("$zhw======$", "mMovePathView1 " + String.valueOf(mMovePathView1));

        if (mMovePathView1 != null) {
            mMovePathView1.reset();
            FrameLayout parent = (FrameLayout) mMovePathView1.getParent();
            parent.removeView(mMovePathView1);
            mUiSettings.setAllGesturesEnabled(true);
            mMovePathView1 = null;
            //上传数据到后台
            Toast.makeText(this, "绘制成功", Toast.LENGTH_SHORT).show();
        }
    }

    public void again(View view) {
        if (mMovePathView1 != null) {
            mMovePathView1.reset();
            Toast.makeText(this, "重新绘制", Toast.LENGTH_SHORT).show();
        }
    }

    public void delete(View view) {
        if (mMovePathView1 != null) {
            mMovePathView1.reset();
            mMovePathView1.reset();
            FrameLayout parent = (FrameLayout) mMovePathView1.getParent();
            parent.removeView(mMovePathView1);
            mUiSettings.setAllGesturesEnabled(true);
            mMovePathView1 = null;
            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
        }
    }
}
